#coding: utf-8
import urllib2, cookielib, urllib, yaml, json
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
import sys
# sys.path.append('/root/cmdb/mysite')
sys.path.append('C:/workspace/mysite')

from mysite.settings import salt_api_url,salt_api_pass,salt_api_user,DATABASES
import MySQLdb

class salt_api_token:
    def __init__(self, data, url, token=None):
        self.data = data
        self.url = url
        self.headers = {
            'User-agent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
            "Accept": "application/x-yaml",
        }
        if token:
            self.headers.update(token)

    def run(self):
        req = requests.post(self.url, headers=self.headers, data=self.data, verify=False)
        context = req.text
        return yaml.load(context)

if __name__ =="__main__":
        # print minions
    try:
        conn=MySQLdb.connect(host=DATABASES['default']['HOST'],user=DATABASES['default']['USER'],
                             passwd=DATABASES['default']['PASSWORD'],db=DATABASES['default']['NAME'],port=int(DATABASES['default']['PORT']))
        cur=conn.cursor()
        cur.execute('select id,minions from salt_node_list')
        res = cur.fetchall()
        dataExists = []
        for idx in res:
            dataExists.append(idx[1])
        #获取所有节点
        data = {'username':salt_api_user,'password':salt_api_pass,"eauth":"pam"}
        url= salt_api_url + 'login'
        test=salt_api_token(data,url)
        key = test.run()
        token = key['return'][0]['token']
        print token
        list = salt_api_token({"client": 'wheel', "fun": "key.list_all", }, salt_api_url, {"X-Auth-Token": token} )
        list = list.run()

        for i in list["return"]:
            minions = i["data"]["return"]["minions"]
            for minion in minions:
                if minion not in dataExists:
                    sql = 'insert into salt_node_list set minions="' + minion + '"'
                    print sql
                    cur.execute(sql)
            minions_pre = i["data"]["return"]["minions_pre"]
            for minionPre in minions_pre:
                if minionPre not in dataExists:
                    sql = 'insert into salt_node_list set minions="' + minionPre + '",key_status=0'
                    print sql
                    cur.execute(sql)
        conn.commit()
        cur.close()
        conn.close()
    except MySQLdb.Error,e:
        print "Mysql Error %d: %s" % (e.args[0], e.args[1])

